<?php
namespace IKPHP\Common\Models;

use IKPHP\Common\Models\BaseModel;
use IKPHP\Common\Models\User;
use IKPHP\Common\Models\VirtualModel;

class LikeModel extends BaseModel
{
	public $id;
	public $typeid;
	public $type;
	public $content;
	public $userid;
	public $addtime;
	public $count_like;	
		
    public function getSource()
    {
        return IK."like";
    } 
    //更新后重新计算评论
    public function afterCreate(){
    	//计算评论数
    	$count = self::count("typeid='$this->typeid'"); 
        //更新模型记录集
        $vimodel = new VirtualModel();
		$vimodel->setviSource($this->type);
		$pkey = $vimodel->getPk();
		$strMod = $vimodel->findFirst(array('conditions'=>"$pkey = $this->typeid")); 
		$strMod->count_like = $count;
		$this->count_like = $count;
		$strMod->save();  	
    }     
    //判断用户是否已经喜欢过了
    public static function isLiked($uid,$typeid,$type){
    	$count = self::count("typeid='$typeid' AND type='$type' AND userid='$uid'");
    	if($count>0){
    		return true;
    	}
    	return false;
    }
	//谁喜欢了该模型
	public static function getLikeUser($typeid, $type, $limit = 6){
		$where = array (
				'conditions'=>"typeid='$typeid' AND type='$type'",
				'order'=> 'addtime desc',
		); 		
		!empty($limit) && $where['limit'] = $limit;
		$results = self::find($where);
		$result = array();
		if(count($results)>0){
			foreach($results->toArray() as $key=>$item){
				$result[] = User::getOneUser($item['userid']);
			}
		}
		return $result;			
	} 
	//用户喜欢的模型数
	public static function countUserLikeByType($uid, $type){
		$count = self::count("type='$type' AND userid='$uid'");
		if($count>0){
			return $count;
		}
		return 0;
	}        	   
}
